Imports System.Runtime.InteropServices
Imports SEInstallDataLib
Imports SolidEdgeFramework

Imports System.Xml


Public Class Form1





    Public seType As System.Type
    Public seApp As SolidEdgeFramework.Application = Nothing
    Public objSEEC As SolidEdgeFramework.SolidEdgeTCE = Nothing


    Public strMajorVersion As String
    Public strBulkLoaderPath As String
    Public blnV18Loaded As Boolean
    Public blnV19Loaded As Boolean
    Public blnV20Loaded As Boolean

    Public strTCConnectionFolder As String = ""
    Public strToplevelAssebly As String = ""
    Public strSE3DDoc As String = ""
    Public strCompaniondraftDoc(0) As String
    Public arrayOfFilesToBePackaged As ArrayList
    Public blnSEAlreadyRunning As Boolean = False
    Public FSO As Scripting.FileSystemObject = Nothing
    Public otext As Scripting.TextStream = Nothing
    Public objRootNode As TreeNode = Nothing
    Public strAppPath As String
    Public oiniFile As Scripting.TextStream = Nothing
    Public OOTBSEECRevRules As ArrayList
    Public ListOfFilesActuallyCheckedOut As ArrayList
    Public strRevRuleToUse As String = ""








    Sub oReleaseObject(ByVal obj As Object)

        '******* Added because of .NET
        If Not (obj Is Nothing) Then
            Try
                Marshal.FinalReleaseComObject(obj)
            Catch ex As Exception
                obj = Nothing
            End Try

        End If



    End Sub
    Public Sub oForceGarbageCollection()
        Try
            GC.Collect(GC.MaxGeneration())
            GC.WaitForPendingFinalizers()
            GC.Collect(GC.MaxGeneration())
        Catch ex As Exception

        End Try
    End Sub
    Sub ConnectToSolidEdge()


        Try
            seApp = Marshal.GetActiveObject("SolidEdge.Application")
            blnSEAlreadyRunning = True
            Exit Sub
        Catch ex As Exception

            Me.Label10.Text = "Starting Solid Edge ....please wait."
            Me.Label10.Refresh()

            Try
                seApp = Activator.CreateInstance(seType)
            Catch ex1 As Exception
                MsgBox("Can not connect to Solid Edge" + ex1.Message)
                End
            End Try


        End Try




       

    End Sub

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        seType = Type.GetTypeFromProgID("SolidEdge.Application")


        ' Adds a ToolTip control (ToolTip1) to the form.
        ToolTip1.SetToolTip(Me.CheckBox1, "Components that are 'checked' below will be left Checked-Out in Teamcenter")

        Me.Label10.Text = ""
        Me.Label10.Refresh()
        Dim jj As Integer = 0

        Dim strTmpString As String = ""
        'ReDim OOTBSEECRevRules(11)

        OOTBSEECRevRules = New ArrayList
        OOTBSEECRevRules.Add("Any Status; No Working")
        OOTBSEECRevRules.Add("Any Status; Working")
        OOTBSEECRevRules.Add("Latest Released")
        OOTBSEECRevRules.Add("Latest Working")
        OOTBSEECRevRules.Add("Latest by Alpha Rev Order")
        OOTBSEECRevRules.Add("Latest by Creation Date")
        OOTBSEECRevRules.Add("Precise Only")
        OOTBSEECRevRules.Add("Precise; Any Status")
        OOTBSEECRevRules.Add("Precise; Working")
        OOTBSEECRevRules.Add("Working(Curr Group);Any Status")
        OOTBSEECRevRules.Add("Working(Curr User);Any Status")
        OOTBSEECRevRules.Add("Working; Any Status")
       

        
        Try
            strAppPath = System.IO.Path.GetDirectoryName( _
                          System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
        Catch ex As Exception
            ' MsgBox(StrCanNotFindINIFile, MsgBoxStyle.OkOnly)
            Exit Sub
        End Try

        strAppPath = Microsoft.VisualBasic.Mid(strAppPath, 7, Microsoft.VisualBasic.Len(strAppPath))

        '******* Added because of .NET
        Try
            MyMessageFilter.MessageFilter.Register()
        Catch ex As Exception
            MsgBox("Error registering message filter.")
            End
        End Try
        '******* Added because of .NET
        If FSO Is Nothing Then
            FSO = New Scripting.FileSystemObject
        End If
        Me.CBRevisionRule.Items.Clear()

        If FSO.FileExists(strAppPath + "\Input.ini") = True Then
            oiniFile = FSO.OpenTextFile(strAppPath + "\Input.ini", Scripting.IOMode.ForReading, False, Scripting.Tristate.TristateUseDefault)
            Do While Not oiniFile.AtEndOfStream
                strTmpString = oiniFile.ReadLine
                If InStr(strTmpString, "LOGIN=", CompareMethod.Text) <> 0 Then
                    Me.TxtUserName.Text = Mid(strTmpString, 7, Len(strTmpString))
                End If
                If InStr(strTmpString, "PASSWORD=", CompareMethod.Text) <> 0 Then
                    Me.TxtPassword.Text = Mid(strTmpString, 10, Len(strTmpString))
                End If
                If InStr(strTmpString, "REVISION_RULE=", CompareMethod.Text) <> 0 Then
                    Dim strData As String = Mid(strTmpString, 15, Len(strTmpString))
                    Dim arrData As String() = strData.Split(",")
                    Me.CBRevisionRule.Text = Mid(arrData(0), 9, Len(arrData(0)))
                    For jj = 1 To arrData.Length - 1
                        Me.CBRevisionRule.Items.Add(arrData(jj))
                    Next
                End If
            Loop
            oiniFile.Close()
        Else
            For jj = 0 To OOTBSEECRevRules.Count - 1
                Me.CBRevisionRule.Items.Add(OOTBSEECRevRules(jj))
            Next

        End If



        Try
            Dim install As New SEInstallDataClass
            strMajorVersion = install.GetMajorVersion

            strBulkLoaderPath = install.GetInstalledPath
            If CInt(install.GetMajorVersion) = 18 Then
                blnV18Loaded = True
            Else
                blnV18Loaded = False
            End If

            If CInt(install.GetMajorVersion) = 19 Then
                blnV19Loaded = True
            Else
                blnV19Loaded = False
            End If

            If CInt(install.GetMajorVersion) >= 20 Then
                blnV20Loaded = True
                Me.TxtURL.Enabled = True

                ' call sub to pull DB urls from TC
                GetDBUrlsFromXMLFile(strBulkLoaderPath + "\TeamcenterDBList.xml")
            Else
                blnV20Loaded = False
            End If
            oReleaseObject(install)


        Catch ex As Exception
            MsgBox("Error creating Solid Edge info object.", MsgBoxStyle.Critical)
            Exit Sub
        End Try

        Try
            FSO = New Scripting.FileSystemObject

            Me.TextBox1.Text = FSO.GetSpecialFolder(Scripting.SpecialFolderConst.TemporaryFolder).Path
        Catch ex As Exception

        End Try


    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click



      


        Dim NumberofDocToCheckout As Long = 0
        Dim iii As Integer
        ''''''''''Dim ctr As Integer = 0
        Me.Label10.Text = " "
        Me.Label10.Refresh()

        Me.Label10.Text = "Connecting to Solid Edge ....please wait."
        Me.Label10.Refresh()
        ConnectToSolidEdge()
        Try  'log into TC
            seApp.Visible = True
            If blnSEAlreadyRunning = False Then
                seApp.DisplayAlerts = False
            End If

            Me.Label10.Text = "Logging into Teamcenter ....please wait."
            Me.Label10.Refresh()

            objSEEC = seApp.SolidEdgeTCE
            objSEEC.SetTeamCenterMode(True)
            If Me.TxtPassword.Text = "" Then
                objSEEC.ValidateLogin(Me.TxtUserName.Text, "", "", "", Me.TxtURL.Text)
            Else
                objSEEC.ValidateLogin(Me.TxtUserName.Text, Me.TxtPassword.Text, "", "", Me.TxtURL.Text)
            End If
        Catch ex As Exception
            MsgBox("Erroring loging into Teamcenter with SEEC -> " + ex.Message)
            End
        End Try

        System.Windows.Forms.Cursor.Current = Cursors.WaitCursor

        Try  ' add the info text file of the files exported.

            If (FSO Is Nothing) Then
                FSO = New Scripting.FileSystemObject
            Else
                otext = FSO.CreateTextFile(Me.TextBox1.Text + "\ExportofItem_" + _
                    Me.txtitemID.Text + "-" + Me.Txtrevision.Text + "_DO_NOT_DELETE.txt", True, False)
            End If

        Catch ex As Exception

        End Try

        otext.WriteLine("Machine used to export:" + My.Computer.Name)
        otext.WriteLine("User:" + Me.TxtUserName.Text)
        otext.WriteLine("Date:" + Now.Date.ToString)
        otext.WriteLine("Top Level Assembly Exported:" + Me.txtitemID.Text + "\" + Me.Txtrevision.Text)
        otext.WriteLine("Revision Rule used:" + Me.CBRevisionRule.Text)


        Try
            objSEEC.GetPDMCachePath(strTCConnectionFolder)

            otext.WriteLine("SEEC cache location:" + strTCConnectionFolder)
            otext.WriteLine("Folder that files were copied to:" + Me.TextBox1.Text)

            arrayOfFilesToBePackaged = New ArrayList
            ListOfFilesActuallyCheckedOut = New ArrayList

            Dim ctrNode As Integer
            Dim jj As Integer
            ctrNode = Me.tvBOM.Nodes.Count
            For jj = 0 To ctrNode - 1
                If jj = 0 Then
                    Me.Label10.Text = "processing linked Teamcenter item revision 1 of " + ctrNode.ToString + " ....please wait."
                    Me.Label10.Refresh()
                Else
                    Me.Label10.Text = "processing linked Teamcenter item revision " + jj.ToString + " of " + ctrNode.ToString + " ....please wait."
                    Me.Label10.Refresh()
                End If

                ReadNodes(Me.tvBOM.Nodes.Item(jj))

            Next



        Catch ex As Exception

        End Try


        Try    ' copy the exported files out to the selected unmanaged folder

            Dim oFile As Scripting.File = Nothing

            For iii = 0 To arrayOfFilesToBePackaged.Count - 1
                If (FSO Is Nothing) Then
                    FSO = New Scripting.FileSystemObject
                Else
                    FSO.CopyFile(strTCConnectionFolder + "\" + arrayOfFilesToBePackaged(iii), Me.TextBox1.Text + "\" + arrayOfFilesToBePackaged(iii))
                    If Me.RBAllAvailable.Checked = True Then  'remove read only from all files
                        oFile = FSO.GetFile(Me.TextBox1.Text + "\" + arrayOfFilesToBePackaged(iii))
                        oFile.Attributes = Scripting.FileAttribute.Normal
                    End If

                    If Me.RBOnlyCheckedOutAvailable.Checked = True Then
                        If ListOfFilesActuallyCheckedOut.Contains(arrayOfFilesToBePackaged(iii)) = True Then
                            oFile = FSO.GetFile(Me.TextBox1.Text + "\" + arrayOfFilesToBePackaged(iii))
                            oFile.Attributes = Scripting.FileAttribute.Normal
                        End If

                    End If


                End If

                oFile = Nothing
            Next
        Catch ex As Exception
            otext.WriteLine("Error copying file->" + Me.TextBox1.Text + "\" + arrayOfFilesToBePackaged(iii))
        End Try


        otext.Close()
        Me.Label10.Text = "Finished"
        Me.Label10.Refresh()

        If blnSEAlreadyRunning = False Then
            seApp.Quit()
        End If


        oReleaseObject(seApp)
        Me.Button1.Enabled = False
        Me.Button5.Enabled = True


        '******* Added because of .NET
        Try
            MyMessageFilter.MessageFilter.Revoke()
        Catch ex As Exception
            MsgBox("Error revoking the message filter.")
        End Try
        '******* Added because of .NET


        System.Windows.Forms.Cursor.Current = Cursors.Default


    End Sub


    Public Function GetDBUrlsFromXMLFile(ByVal xmlFileName As String) As String

        Dim m_xmld As XmlDocument
        Dim m_ComponentsNode As XmlNode = Nothing
        Dim m_ListOfNOdes As XmlNodeList = Nothing
        Dim DBNodes As XmlNodeList = Nothing
        Dim nn As Integer
        Dim m_PropNode As XmlNode = Nothing
        Dim m_SequenceNode As XmlNode = Nothing
        Dim intCtr As Long
        Dim strNodeNAme As String
        Dim strDefaultDB As String = ""
        Dim jj As Integer

        intCtr = 0


        m_xmld = New XmlDocument()
        'Me.LblStatus.Text = "Please wait loading XML file...."
        ' Me.LblStatus.Refresh()
        Try
            m_xmld.Load(xmlFileName)
        Catch ex As Exception
            GetDBUrlsFromXMLFile = ""
            Exit Function
        End Try
        Try

            'Me.LblStatus.Text = " "
            'Me.LblStatus.Refresh()

            m_ComponentsNode = m_xmld.SelectSingleNode("/TeamcenterDBList")
            m_ListOfNOdes = m_ComponentsNode.ChildNodes
            For nn = 0 To m_ListOfNOdes.Count - 1
                strNodeNAme = m_ListOfNOdes.Item(nn).Name.ToString
                If strNodeNAme = "DefaultDatabase" Then
                    strDefaultDB = m_ListOfNOdes.Item(nn).InnerText
                ElseIf strNodeNAme = "Databases" Then
                    m_SequenceNode = m_ListOfNOdes.Item(nn)
                    DBNodes = m_ListOfNOdes.Item(nn).SelectNodes("./Database")
                    For jj = 0 To DBNodes.Count - 1
                        m_PropNode = DBNodes.Item(jj)
                        Me.TxtURL.Items.Add(m_PropNode.FirstChild.InnerText)
                    Next

                End If



            Next
            Me.TxtURL.Text = strDefaultDB
        Catch ex As Exception
            GetDBUrlsFromXMLFile = ""
        End Try
        oReleaseObject(m_PropNode)
        oReleaseObject(DBNodes)
        oReleaseObject(m_SequenceNode)
        oReleaseObject(m_ListOfNOdes)
        oReleaseObject(m_ComponentsNode)
        oReleaseObject(m_xmld)




        GetDBUrlsFromXMLFile = ""



    End Function
    Public Function CheckOutItemID(ByVal strItemId As String, ByVal strIDrev As String) As Boolean

        Dim ListofFiles As Object = Nothing
        Dim NumberOfFiles As Integer
        Dim ii As Integer = 0
        Dim ctr As Integer = 0
        Dim strFilenametoCheckOut As String = ""


        '****** at some point need to make sure this function will checkout multiple drafts!!!!!!!

        objSEEC.GetListOfFilesFromTeamcenterServer(strItemId, _
                            strIDrev, ListofFiles, NumberOfFiles)
        If NumberOfFiles = 0 Then
            Exit Function
        End If

        For ii = 0 To NumberOfFiles - 1  ' get the list of SE docs in the given item revision in TC

            If InStr(UCase(ListofFiles(ii)), ".DFT", CompareMethod.Text) <> 0 Then
                If ctr > 0 Then
                    ReDim Preserve strCompaniondraftDoc(ctr + 1)
                End If
                strCompaniondraftDoc(ctr) = ListofFiles(ii)
                arrayOfFilesToBePackaged.Add(ListofFiles(ii))
                ctr = ctr + 1
            Else
                strFilenametoCheckOut = ListofFiles(ii)
                arrayOfFilesToBePackaged.Add(ListofFiles(ii))
            End If
        Next

        Try
            objSEEC.CheckOutDocumentsFromTeamCenterServer(strItemId, strIDrev, False, strFilenametoCheckOut, DocumentDownloadLevel.SEECDownloadAllLevel)
            otext.WriteLine("left Checked-out>" + strItemId + ":" + strIDrev + ":" + strFilenametoCheckOut)
            ListOfFilesActuallyCheckedOut.Add(strFilenametoCheckOut)
        Catch ex As Exception
            otext.WriteLine("NOT left Checked-out>" + strItemId + ":" + strIDrev + ":" + strFilenametoCheckOut)
        End Try

        Try
            For ii = 0 To ctr - 1
                objSEEC.CheckOutDocumentsFromTeamCenterServer(strItemId, strIDrev, False, strCompaniondraftDoc(ii), DocumentDownloadLevel.SEECDownloadTopLevel)
                ListOfFilesActuallyCheckedOut.Add(strCompaniondraftDoc(ii))
                otext.WriteLine("left Checked-out>" + strItemId + ":" + strIDrev + ":" + strCompaniondraftDoc(ii))

            Next

        Catch ex As Exception
            otext.WriteLine("NOT left Checked-out>" + strItemId + ":" + strIDrev + ":" + strCompaniondraftDoc(ii))
        End Try



    End Function


    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        With FolderBrowserDialog1

            .ShowDialog()
            Me.TextBox1.Text = .SelectedPath
        End With
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click


        Dim blnToplevelnodeAlreadyCreated As Boolean = False
        Dim strTemporary As String = ""
        Dim pp As Integer = 0
        System.Windows.Forms.Cursor.Current = Cursors.WaitCursor

        strRevRuleToUse = Me.CBRevisionRule.Text

        Try
            If FSO.FileExists(strAppPath + "\Input.ini") = True Then
                FSO.DeleteFile(strAppPath + "\Input.ini", True)
            End If

            oiniFile = FSO.CreateTextFile(strAppPath + "\Input.ini", True)
            oiniFile.WriteLine("LOGIN=" + Me.TxtUserName.Text)
            oiniFile.WriteLine("PASSWORD=" + Me.TxtPassword.Text)

            strTemporary = "REVISION_RULE=DEFAULT:" + Me.CBRevisionRule.Text + ","
            For pp = 0 To Me.CBRevisionRule.Items.Count - 1
                strTemporary = strTemporary + Me.CBRevisionRule.Items(pp) + ","
            Next

            If OOTBSEECRevRules.Contains(Me.CBRevisionRule.Text) = False Then
                strTemporary = strTemporary + Me.CBRevisionRule.Text
            Else
                strTemporary = Mid(strTemporary, 1, Len(strTemporary) - 1)
            End If



            oiniFile.WriteLine(strTemporary)
            oiniFile.Close()
            strTemporary = ""
        Catch ex As Exception

        End Try

        Dim objChildNode As TreeNode = Nothing


        If (Me.tvBOM.GetNodeCount(False) = 1) Then
            ReleaseNode(Me.tvBOM.Nodes.Item(0))
            Me.tvBOM.Nodes.Clear()
        End If


        'Me.tvBOM.Visible = False

        Me.Label10.Text = "Connecting to Solid Edge ..... please wait."
        Me.Label10.Refresh()

        ConnectToSolidEdge()
        Try  'log into TC
            seApp.Visible = True
            If blnSEAlreadyRunning = False Then
                seApp.DisplayAlerts = False
            End If



            Me.Label10.Text = "Logging into Teamcenter ..... please wait."
            Me.Label10.Refresh()

            objSEEC = seApp.SolidEdgeTCE
            objSEEC.SetTeamCenterMode(True)
            objSEEC.GetPDMCachePath(strTCConnectionFolder)
            If Me.TxtPassword.Text = "" Then
                objSEEC.ValidateLogin(Me.TxtUserName.Text, "", "", "", Me.TxtURL.Text)
            Else
                objSEEC.ValidateLogin(Me.TxtUserName.Text, Me.TxtPassword.Text, "", "", Me.TxtURL.Text)
            End If
        Catch ex As Exception
            MsgBox("Erroring loging into Teamcenter with SEEC -> " + ex.Message)
            End
        End Try



        Dim NumberOfLinkedDocs1 As Long
        Dim ListOfItemRevIDs1 As Object = Nothing
        Dim ListOfFileSpecs1 As Object = Nothing
        Dim ListofFiles2 As Object = Nothing
        Dim NumberOfFiles2 As Integer
        Dim iii As Integer = 0
        Dim ctr1 As Integer = 0
        Dim NumberofDocToCheckout1 As Integer



        Try
            Me.Label10.Text = "Determining list of files ..... please wait."
            Me.Label10.Refresh()
            objSEEC.GetListOfFilesFromTeamcenterServer(Me.txtitemID.Text, _
            Me.Txtrevision.Text, ListofFiles2, NumberOfFiles2)
        Catch ex As Exception
            MsgBox("error getting list of files under given item id:  " + Me.txtitemID.Text + "/" + Me.Txtrevision.Text + " ->" + ex.Message)
        End Try
       
        If NumberOfFiles2 = 0 Then
            Exit Sub
        End If

        For iii = 0 To NumberOfFiles2 - 1  ' get the list of SE docs in the given item revision in TC
            If InStr(UCase(ListofFiles2(iii)), ".ASM", CompareMethod.Text) <> 0 Then
                strToplevelAssebly = ListofFiles2(iii)
            End If     
        Next

        For iii = 0 To NumberOfFiles2 - 1  ' get the list of SE docs in the given item revision in TC
            If InStr(UCase(ListofFiles2(iii)), ".ASM", CompareMethod.Text) <> 0 Then
                strToplevelAssebly = ListofFiles2(iii)
                If blnToplevelnodeAlreadyCreated = False Then
                    objRootNode = Me.tvBOM.Nodes.Add(Me.txtitemID.Text + "/" + Me.Txtrevision.Text + " -> " + strToplevelAssebly)
                End If

            End If
            If InStr(UCase(ListofFiles2(iii)), ".DFT", CompareMethod.Text) <> 0 Then

                If ctr1 > 0 Then
                    ReDim Preserve strCompaniondraftDoc(ctr1 + 1)
                End If
                strCompaniondraftDoc(ctr1) = ListofFiles2(iii)

                If objRootNode Is Nothing Then
                    If blnToplevelnodeAlreadyCreated = False Then
                        objRootNode = Me.tvBOM.Nodes.Add(Me.txtitemID.Text + "/" + Me.Txtrevision.Text + " -> " + strToplevelAssebly)
                        blnToplevelnodeAlreadyCreated = True
                    End If
                End If
                objChildNode = objRootNode.Nodes.Add(Me.txtitemID.Text + "/" + Me.Txtrevision.Text + " -> " + ListofFiles2(iii))

                ctr1 = ctr1 + 1
            End If
        Next



        ' added the specified top level assembly and it's companion draft now get the rest of linked files
        Try   'NumberOfLinkedDocs returns the instanced or total number of linked files NOT unique
            objSEEC.GetBomStructure(Me.txtitemID.Text, Me.Txtrevision.Text, Me.CBRevisionRule.Text, _
            True, NumberOfLinkedDocs1, ListOfItemRevIDs1, ListOfFileSpecs1)
        Catch ex As Exception
            'raise an error and do something

        End Try

        If NumberOfLinkedDocs1 = 0 Then
            Me.Label10.Text = "No linked documents found based on input revision rule."
            Me.Label10.Refresh()
            Exit Sub
        End If


        NumberofDocToCheckout1 = ListOfItemRevIDs1.getupperbound(0)

        For iii = 0 To NumberofDocToCheckout1
            If iii = 0 Then
                Me.Label10.Text = "expanding out component 1 of " + NumberofDocToCheckout1.ToString
                Me.Label10.Refresh()
            Else
                Me.Label10.Text = "expanding out component " + iii.ToString + " of " + NumberofDocToCheckout1.ToString
                Me.Label10.Refresh()
            End If
            ExpandItemID(ListOfItemRevIDs1(iii, 0), ListOfItemRevIDs1(iii, 1))
            Me.tvBOM.ExpandAll()
        Next

        Me.tvBOM.ExpandAll()


        Me.Button1.Enabled = True

        Me.Label10.Text = "All entries list will be exported from Teamcenter.  Only the checked entries will be left Checked-Out in Teamcenter.  Click OK to process."
        'For Japp only
        'Me.Label10.Text = " Click OK to export all entries listed above from Teamcenter.  "
        Me.Label10.Refresh()

        System.Windows.Forms.Cursor.Current = Cursors.Default

    End Sub


    'This recursive function drills down to the lowest children and
    ' call ReleaseComObject() back up the tree.  This helps ensure we
    ' release the objects in the order they were obtained.
    Private Sub ReleaseNode(ByVal node As TreeNode)

        For Each childNode As TreeNode In node.Nodes
            ReleaseNode(childNode)
        Next

        If Not (node.Tag Is Nothing) Then
            Try
                Marshal.ReleaseComObject(node.Tag)
                node.Tag = Nothing
            Catch
            End Try
        End If
    End Sub


    Public Function ExpandItemID(ByVal strItemId As String, ByVal strIDrev As String) As Boolean

        Dim ListofFiles As Object = Nothing
        Dim NumberOfFiles As Integer
        Dim ii As Integer = 0
        Dim ctr As Integer = 0
        Dim strFilenametoCheckOut As String = ""
        Dim objChildNode1 As TreeNode = Nothing

        '****** at some point need to make sure this function will checkout multiple drafts!!!!!!!
        Try
            objRootNode = Nothing
            oReleaseObject(objRootNode)
        Catch ex As Exception

        End Try


        Try
            objSEEC.GetListOfFilesFromTeamcenterServer(strItemId, strIDrev, ListofFiles, NumberOfFiles)
            If NumberOfFiles = 0 Then
                Exit Function
            End If

            For ii = 0 To NumberOfFiles - 1  ' get the list of SE docs in the given item revision in TC
                If InStr(UCase(ListofFiles(ii)), ".PAR", CompareMethod.Text) <> 0 Or InStr(UCase(ListofFiles(ii)), ".PSM", CompareMethod.Text) <> 0 Or InStr(UCase(ListofFiles(ii)), ".ASM", CompareMethod.Text) <> 0 Or InStr(UCase(ListofFiles(ii)), ".PWD", CompareMethod.Text) <> 0 Then
                    strFilenametoCheckOut = ListofFiles(ii)
                    objRootNode = Me.tvBOM.Nodes.Add(strItemId + "/" + strIDrev + " -> " + ListofFiles(ii))
                    If InStr(UCase(ListofFiles(ii)), ".PAR", CompareMethod.Text) <> 0 Or InStr(UCase(ListofFiles(ii)), ".PSM", CompareMethod.Text) <> 0 Then
                        recursiveExpandItem(strItemId, strIDrev, objRootNode, strFilenametoCheckOut)
                    End If

                End If
            Next

            For ii = 0 To NumberOfFiles - 1  ' get the list of SE docs in the given item revision in TC
                If InStr(UCase(ListofFiles(ii)), ".DFT", CompareMethod.Text) <> 0 Then
                    If ctr > 0 Then
                        ReDim Preserve strCompaniondraftDoc(ctr + 1)
                    End If
                    strCompaniondraftDoc(ctr) = ListofFiles(ii)
                    objChildNode1 = objRootNode.Nodes.Add(strItemId + "/" + strIDrev + " -> " + ListofFiles(ii))
                    ctr = ctr + 1
                Else

                End If
            Next
        Catch ex As Exception

        End Try

       



    End Function


    Public Sub recursiveExpandItem(ByVal strItemId As String, ByVal strIDrev As String, ByVal oRootNode As TreeNode, ByVal strDatasetName As String)

        Dim ListofFilesRec As Object = Nothing

        Dim jj As Integer = 0
        Dim ii As Integer = 0

        Dim strFilenametoCheckOutRec As String = ""
        Dim objChildNode1Rec As TreeNode = Nothing


        Try
            objSEEC.GetListOfIndirectFilesForGivenFile(strItemId, strIDrev, strDatasetName, strRevRuleToUse, "", ListofFilesRec)

            If ListofFilesRec.length > 0 Then
                objSEEC.CheckOutDocumentsFromTeamCenterServer(strItemId, strIDrev, True, , DocumentDownloadLevel.SEECDownloadFirstLevel)
            End If

            For ii = 0 To ListofFilesRec.length - 1
                If ListofFilesRec(ii) <> strDatasetName Then
                    Dim strNewItemID As String = ""
                    Dim strNewItemRev As String = ""
                    objSEEC.GetDocumentUID(strTCConnectionFolder + "\" + ListofFilesRec(ii), strNewItemID, strNewItemRev) ' has to be in the cache first
                    objChildNode1Rec = Me.tvBOM.Nodes.Add(strNewItemID + "/" + strNewItemRev + " -> " + ListofFilesRec(ii))
                    'check for companion draft files for each of the linked files
                    Dim ListofFilesRec1 As Object = Nothing
                    Dim NumberOfFilesRec As Integer = 0
                    Dim ctr As Integer = 0
                    objSEEC.GetListOfFilesFromTeamcenterServer(strNewItemID, strNewItemRev, ListofFilesRec1, NumberOfFilesRec)

                    For jj = 0 To NumberOfFilesRec - 1  ' get the list of SE docs in the given item revision in TC
                        If InStr(UCase(ListofFilesRec1(jj)), ".DFT", CompareMethod.Text) <> 0 Then
                            If ctr > 0 Then
                                ReDim Preserve strCompaniondraftDoc(ctr + 1)
                            End If
                            strCompaniondraftDoc(ctr) = ListofFilesRec1(jj)
                            objChildNode1Rec.Nodes.Add(strNewItemID + "/" + strNewItemRev + " -> " + ListofFilesRec1(jj))
                            ctr = ctr + 1
                        Else

                        End If
                    Next


                End If
            Next


        Catch ex As Exception

        End Try


    End Sub
    Public Sub junk()

        ''''''Dim ListofFiles As Object = Nothing
        ''''''Dim NumberOfFiles As Integer
        ''''''Dim ii As Integer = 0
        'Dim FilesToDelete() As Object
        'Dim Ans As MsgBoxResult

        ' Ans = MsgBox("WARNING ****** This utility will DELETE your current SEEC cache.  Ckick the OK button to delete the current cache and continue or Cancel to abort this utility", MsgBoxStyle.OkCancel)
        'If Ans = MsgBoxResult.Cancel Then
        '    Exit Sub
        'End If



        'Try   'NumberOfLinkedDocs returns the instanced or total number of linked files NOT unique
        '    objSEEC.GetBomStructure(Me.txtitemID.Text, Me.Txtrevision.Text, Me.CBRevisionRule.Text, True, NumberOfLinkedDocs, ListOfItemRevIDs, ListOfFileSpecs)
        'Catch ex As Exception
        '    raise an error and do something

        'End Try
    End Sub

    Private Sub ReadNodes(ByVal node As TreeNode)

        Dim strItem_ID As String = ""
        Dim strID_rev As String = ""
        Dim strFilename_To_CheckOut As String = ""
        Dim nstart As Integer = 0
        Dim pstart As Integer = 0


        objSEEC = seApp.SolidEdgeTCE

        nstart = InStr(node.Text, "/", CompareMethod.Text)
        If nstart <> 0 Then
            strItem_ID = Trim(Mid(node.Text, 1, nstart - 1))
            pstart = InStr(node.Text, ">", CompareMethod.Text)
            If pstart <> 0 Then
                strID_rev = Trim(Mid(node.Text, nstart + 1, pstart - 2 - nstart))
                strFilename_To_CheckOut = Trim(Mid(node.Text, pstart + 1, Len(node.Text)))
            End If

        End If

        If node.Checked = True Then

            Try
                objSEEC.CheckOutDocumentsFromTeamCenterServer(strItem_ID, strID_rev, False, strFilename_To_CheckOut, DocumentDownloadLevel.SEECDownloadTopLevel)
                otext.WriteLine("Copied and left Checked-out:" + strItem_ID + ":" + strID_rev + ":" + strFilename_To_CheckOut)
                ListOfFilesActuallyCheckedOut.Add(strFilename_To_CheckOut)
                arrayOfFilesToBePackaged.Add(strFilename_To_CheckOut)
            Catch ex As Exception
                Try
                    objSEEC.CheckOutDocumentsFromTeamCenterServer(strItem_ID, strID_rev, True, strFilename_To_CheckOut, DocumentDownloadLevel.SEECDownloadTopLevel)
                    otext.WriteLine("Copied but NOT left Checked-out:" + strItem_ID + ":" + strID_rev + ":" + strFilename_To_CheckOut)
                    arrayOfFilesToBePackaged.Add(strFilename_To_CheckOut)
                Catch ex1 As Exception
                    otext.WriteLine("error downloading file " + strFilename_To_CheckOut)
                End Try
                
            End Try

        ElseIf node.Checked = False Then
            Try
                objSEEC.CheckOutDocumentsFromTeamCenterServer(strItem_ID, strID_rev, True, strFilename_To_CheckOut, DocumentDownloadLevel.SEECDownloadTopLevel)
                otext.WriteLine("Copied but NOT left Checked-out:" + strItem_ID + ":" + strID_rev + ":" + strFilename_To_CheckOut)
                arrayOfFilesToBePackaged.Add(strFilename_To_CheckOut)
            Catch ex As Exception
                otext.WriteLine("error downloading file " + strFilename_To_CheckOut)
            End Try

        End If


        For Each childNode As TreeNode In node.Nodes

            nstart = InStr(childNode.Text, "/", CompareMethod.Text)
            If nstart <> 0 Then
                strItem_ID = Trim(Mid(childNode.Text, 1, nstart - 1))
                pstart = InStr(childNode.Text, ">", CompareMethod.Text)
                If pstart <> 0 Then
                    strID_rev = Trim(Mid(childNode.Text, nstart + 1, pstart - 2 - nstart))
                    strFilename_To_CheckOut = Trim(Mid(childNode.Text, pstart + 1, Len(childNode.Text)))
                End If

            End If

            If childNode.Checked = True Then
                Try
                    objSEEC.CheckOutDocumentsFromTeamCenterServer(strItem_ID, strID_rev, False, strFilename_To_CheckOut, DocumentDownloadLevel.SEECDownloadTopLevel)
                    otext.WriteLine("Copied and left Checked-out:" + strItem_ID + ":" + strID_rev + ":" + strFilename_To_CheckOut)
                    ListOfFilesActuallyCheckedOut.Add(strFilename_To_CheckOut)
                    arrayOfFilesToBePackaged.Add(strFilename_To_CheckOut)
                Catch ex As Exception
                    Try
                        objSEEC.CheckOutDocumentsFromTeamCenterServer(strItem_ID, strID_rev, True, strFilename_To_CheckOut, DocumentDownloadLevel.SEECDownloadTopLevel)
                        otext.WriteLine("Copied but NOT left Checked-out:" + strItem_ID + ":" + strID_rev + ":" + strFilename_To_CheckOut)
                        arrayOfFilesToBePackaged.Add(strFilename_To_CheckOut)
                    Catch ex1 As Exception
                        otext.WriteLine("error downloading file " + strFilename_To_CheckOut)
                    End Try

                End Try

            ElseIf childNode.Checked = False Then
                Try
                    objSEEC.CheckOutDocumentsFromTeamCenterServer(strItem_ID, strID_rev, True, strFilename_To_CheckOut, DocumentDownloadLevel.SEECDownloadTopLevel)
                    otext.WriteLine("Copied but NOT Checked-out:" + strItem_ID + ":" + strID_rev + ":" + strFilename_To_CheckOut)
                    arrayOfFilesToBePackaged.Add(strFilename_To_CheckOut)
                Catch ex As Exception
                    otext.WriteLine("error downloading file " + strFilename_To_CheckOut)
                End Try

            End If



            If childNode.Nodes.Count > 0 Then
                ReadNodes(childNode)
            End If

        Next


    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click



        End

    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
        Dim strPathToNotpad As String
        Try

            If FSO Is Nothing Then
                FSO = New Scripting.FileSystemObject
            End If
            strPathToNotpad = FSO.GetSpecialFolder(Scripting.SpecialFolderConst.WindowsFolder).Path + "\notepad.exe"

            Call Shell(strPathToNotpad + " " + Me.TextBox1.Text + "\ExportofItem_" + _
                    Me.txtitemID.Text + "-" + Me.Txtrevision.Text + "_DO_NOT_DELETE.txt", AppWinStyle.NormalFocus)
        Catch ex As Exception
            MsgBox("Error displaying file", MsgBoxStyle.OkOnly)
        End Try
    End Sub

    Private Sub RadioButton1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)


    End Sub


    Private Sub CheckNodes(ByVal node As TreeNode)

       
      

        Try
            node.Checked = True
            For Each childNode As TreeNode In node.Nodes
                childNode.Checked = True
                If childNode.Nodes.Count > 0 Then
                    CheckNodes(childNode)
                End If
            Next
        Catch ex As Exception

        End Try

        


    End Sub


    Private Sub UnCheckNodes(ByVal node As TreeNode)


        Dim nstart As Integer = 0
        Dim pstart As Integer = 0

        Try
            node.Checked = False
            For Each childNode As TreeNode In node.Nodes
                childNode.Checked = False
                If childNode.Nodes.Count > 0 Then
                    UnCheckNodes(childNode)
                End If
            Next
        Catch ex As Exception

        End Try

        


    End Sub

    Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
        Dim kk As Integer = 0


        ' Adds a ToolTip control (ToolTip1) to the form.
        ToolTip1.SetToolTip(Me.CheckBox1, "Components that are 'checked' below will be left Checked-Out in Teamcenter")


        If Me.CheckBox1.Checked = True Then   'select all nodes in the tree automatically
            For kk = 0 To Me.tvBOM.Nodes.Count - 1
                CheckNodes(Me.tvBOM.Nodes.Item(kk))
            Next kk

        End If


        If Me.CheckBox1.Checked = False Then   'de-select all nodes in the tree automatically
            For kk = 0 To Me.tvBOM.Nodes.Count - 1
                UnCheckNodes(Me.tvBOM.Nodes.Item(kk))
            Next kk
        End If
    End Sub

    Private Sub ToolTip1_Popup(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PopupEventArgs) Handles ToolTip1.Popup

    End Sub
End Class
